<template>
  <view class="bg-[var(--page-bg-color)] min-h-[100vh]" :style="themeColor()">
    <view class="w-full bg-[var(--page-bg-color)]">
      <view class="pb-[210rpx] relative" :style="headerStyle">
        <!-- #ifdef MP-WEIXIN || APP-PLUS -->
        <top-tabbar
          :data="param"
          :scrollBool="topTabarObj.getScrollBool()"
          class="top-header"
        />
        <!-- #endif -->
        <view
          class="text-[70rpx] leading-[90rpx] text-[#fff] pl-[60rpx] font-500 pt-[77rpx] price-font h-[88rpx]"
        >
          {{ info?.contribution_points || 0 }}
        </view>
        <view class="flex items-center pl-[60rpx] h-[50rpx]">
          <image
            class="h-[36rpx] w-[36rpx] -mb-[4rpx]"
            :src="img('static/resource/images/member/point/icon.png')"
            mode="heightFix"
          />
          <view class="text-[26rpx] leading-[36rpx] text-[#fff] ml-[10rpx]"
            >我的贡献值</view
          >
        </view>
        <view
          v-if="btnShow"
          class="side-tab"
          :style="{ top: topStyle }"
          @click="redirect({ url: '/app/pages/member/digital_asset_detail' })"
        >
          <text class="nc-iconfont nc-icon-jifenduihuanV6xx1 icon"></text>
          <text class="desc">星星豆明细</text>
        </view>
      </view>
      <view class="sidebar-margin flex flex-col mt-[-178rpx] relative">
        <view
          class="w-[322rpx] h-[80rpx] text-[28rpx] text-[#333] font-500 box-border pl-[30rpx] pt-[var(--pad-top-m)] rounded-tl-[var(--rounded-big)] overflow-hidden mb-[-2rpx]"
          :style="{
            backgroundImage:
              'url(' + img('static/resource/images/member/point/top_bg.png') + ') ',
            backgroundSize: '100% 100%',
            backgroundRepeat: 'no-repeat',
          }"
        >
          <text class="leading-[42rpx]">星星豆</text>
        </view>
        <view
          class="flex flex-col items-start px-[30rpx] rounded-[var(--rounded-big)] !rounded-tl-none bg-[#fff] h-[223rpx] box-border"
        >
          <view class="text-[#333] text-[60rpx] py-[30rpx] price-font">{{
            info?.digital_asset || 0
          }}</view>
          <view class="text-[26rpx] py-[20rpx] text-[#999]"
            >星星豆来源：①贡献值购买；②可用积分转换兑换券。</view
          >
        </view>
      </view>
    </view>

    <view class="mt-[var(--top-m)] sidebar-margin card-template">
      <view class="type-content">
        <view class="type-item checked">购买</view>
      </view>
    </view>
    <view class="mt-[var(--top-m)] sidebar-margin card-template">
      <view class="title">购买星星豆数量</view>
      <view class="input-box">
        <input
          v-model.trim="digital_asset"
          type="number"
          placeholder="请输入星星豆数量"
          maxlength="13"
        />
        <view class="btn-right" @click="exchange">全部购买</view>
      </view>
      <view class="title">购买说明</view>
      <view class="text-[#999] text-[26rpx] leading-[54rpx] price-font"
        >1.贡献值购买星星豆比例：{{ buyDigitalAssetsRate }}:1。</view
      >
    </view>
    <view class="mt-[var(--top-m)] sidebar-margin bottom-btn" @click="submit"
      >确认购买</view
    >
    <!-- 支付密码组件 -->
    <pay-local ref="payLocalRef" @success="executeBuy" />
  </view>
</template>

<script setup lang="ts">
import { computed, ref, onMounted } from "vue";
import useMemberStore from "@/stores/member";
import useSystemStore from "@/stores/system";
import { redirect, img, pxToRpx } from "@/utils/common";
import { postBuyDigitalAsset, getBuyDigitalAssetsRate } from "@/app/api/member"; 
import { topTabar } from "@/utils/topTabbar";
import PayLocal from "@/components/pay-local/pay-local.vue";
const memberStore = useMemberStore();
const systemStore: any = useSystemStore();

/********* 自定义头部 - start ***********/
const topTabarObj = topTabar();
let param = topTabarObj.setTopTabbarParam({ title: "星星豆" });
/********* 自定义头部 - end ***********/

// 获取系统状态栏的高度
let menuButtonInfo: any = {};
// #ifdef MP-WEIXIN || MP-BAIDU || MP-TOUTIAO || MP-QQ
menuButtonInfo = uni.getMenuButtonBoundingClientRect();
// #endif
const headerStyle = computed(() => {
  return {
    backgroundImage:
      "url(" +
      img("static/resource/images/member/point/contribution_point_bg.png") +
      ") ",
    backgroundSize: "cover",
    backgroundRepeat: "no-repeat",
    backgroundPosition: "bottom",
    // paddingTop:Object.keys(menuButtonInfo).length?(Number(menuButtonInfo.height) * 2 + menuButtonInfo.top * 2 + 77)+'rpx':'77rpx',
  };
});
const buyDigitalAssetsRate = ref<any>(0); // 贡献值购买星星豆比例

const topStyle = computed(() => {
  let top = "";
  // #ifdef MP
  top = Object.keys(menuButtonInfo).length
    ? pxToRpx(Number(menuButtonInfo.height)) + pxToRpx(menuButtonInfo.top) + 50 + "rpx;"
    : "50rpx";
  // #endif
  // #ifdef APP-PLUS
  top = systemStore.statusBarHeight + 50 + "px";
  // #endif
  return top;
});

//个人信息
const info = computed(() => {
  return memberStore.info;
});

const btnShow = computed(() => {
  return memberStore.buttonAuth.digital_asset || false;
});

const digital_asset = ref<number>(); // 购买数量

// 支付密码组件引用
const payLocalRef = ref();

// 全部购买
const exchange = () => {
  if (buyDigitalAssetsRate.value <= 0) {
    uni.showToast({
      title: "获取购买星星豆比例失败",
      icon: "none",
    });
    return;
  }
  let val = (info.value?.contribution_points || 1) / (buyDigitalAssetsRate.value || 1);
  digital_asset.value = val;
};

// 获取贡献值购买星星豆比例
const getBuyDigitalAssetsRateFn = () => {
  getBuyDigitalAssetsRate().then((res: any) => {
    buyDigitalAssetsRate.value = res.data.value || 0;
  });
};

// 提交购买
const submit = () => {
  if (!info.value.pay_password) {
    uni.showModal({
      title: "提示",
      content: "请先设置支付密码",
      confirmText: "去设置",
      showCancel: false,
      success: (res) => {
        if (res.confirm) {
          redirect({
            url: "/app/pages/paymentSetting/index",
          });
        }
      },
    });
    return;
  }
  
  if (!digital_asset.value || digital_asset.value <= 0) {
    uni.showToast({
      title: "请输入购买数量",
      icon: "none",
    });
    return;
  }
  let val = (info.value?.contribution_points || 1) / (buyDigitalAssetsRate.value || 1);
  if (digital_asset.value > val) {
    uni.showToast({
      title: "贡献值不足",
      icon: "none",
    });
    return;
  }

  // 弹出支付密码输入框
  payLocalRef.value?.open();
};

// 执行购买操作
const executeBuy = () => {
  uni.showLoading({
    title: "购买中...",
    mask: true,
  });
  postBuyDigitalAsset({ digital_asset: digital_asset.value })
    .then((res: any) => {
        digital_asset.value = 0;
      setTimeout(() => {
        uni.showToast({
          title: "购买成功",
          icon: "none",
        });
      }, 1000);
      memberStore.getMemberInfo();
    })
    .finally(() => {
      uni.hideLoading();
    });
};

onMounted(() => {
  getBuyDigitalAssetsRateFn();
});
</script>

<style lang="scss" scoped>
.bg-color {
  background-color: rgba(102, 102, 102, 0.4);
}
.bottom-btn {
  z-index: 999;
  text-align: center;
  color: #fff;
  padding: 20rpx;
  border-radius: 20rpx;
  background-color: #ff3e06;
  &:active {
    opacity: 0.8;
  }
}
</style>
